const car = {
  namespaced: true,
  state() {
    return {
      goodslist: JSON.parse(localStorage.getItem('carxxf2'))?.car.goodslist || []
    }
  },
  mutations: {
    addgoods(state, payload) {
      // 首先判断是否是第一次添加，是的话的数量设置为1否的话数量加1
      const fitem = state.goodslist.find(item => item.iid === payload.iid)
      if (!fitem) {
        payload.number = 1
        payload.ischeck = false
        state.goodslist.push(payload)
      } else {
        fitem.number += 1
      }
    },
    changeallcheck(state, checkstatus) {
      state.goodslist.forEach(item => {
        item.ischeck = checkstatus
      })
    },
    changeitemischeck(state, iid) {
      const index = state.goodslist.findIndex(item => item.iid === iid)
      state.goodslist[index].ischeck = !state.goodslist[index].ischeck
    }
  },
  getters: {
    goodsnum(state) {
      const sum = state.goodslist.reduce((sum, item) => (
        sum += item.number
      ), 0)
      return sum
    },
    allmonery(state) {
      const total = state.goodslist.filter(item => item.ischeck).reduce((sum, item) => (sum += (item.price - 0) * item.number), 0)
      return total
    },
    isallchecked(state) {
      return state.goodslist.filter(item => item.ischeck).length === state.goodslist.length
    }
  }
}
export default car
